package cn.stimd.spring.context.event;

import cn.stimd.spring.beans.factory.SmartInitializingSingleton;
import cn.stimd.spring.context.ApplicationContext;
import cn.stimd.spring.context.ApplicationContextAware;
import cn.stimd.spring.context.ConfigurableApplicationContext;
import org.springframework.core.MethodIntrospector;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public class EventListenerMethodProcessor implements SmartInitializingSingleton, ApplicationContextAware {
    private ConfigurableApplicationContext applicationContext;
    private final Set<Class<?>> nonAnnotatedClasses = Collections.newSetFromMap(new ConcurrentHashMap<>(64));


    @Override
    public void afterSingletonsInstantiated() {
        //遍历所有的单例Bean
        List<String> beanNames = this.applicationContext.getBeanNamesForType(Object.class);
        for (String beanName : beanNames) {
            Class<?> type = this.applicationContext.getType(beanName);
            processBean(beanName, type);
        }
    }


    protected void processBean(final String beanName, final Class<?> targetType) {
        if (!this.nonAnnotatedClasses.contains(targetType)) {
            //寻找所有声明了@EventListener注解的方法
            Map<Method, EventListener> annotatedMethods = MethodIntrospector.selectMethods(targetType,
                    new MethodIntrospector.MetadataLookup<EventListener>() {
                        @Override
                        public EventListener inspect(Method method) {
                            return AnnotatedElementUtils.findMergedAnnotation(method, EventListener.class);
                        }
                    });

            if (CollectionUtils.isEmpty(annotatedMethods)) {
                this.nonAnnotatedClasses.add(targetType);
            }else{
                //为每个监听方法创建一个适配器对象，并添加到监听器集合中
                for (Method method : annotatedMethods.keySet()) {
                    ApplicationListener<?> listener = new ApplicationListenerMethodAdapter(beanName, targetType, method, this.applicationContext);
                    this.applicationContext.addApplicationListener(listener);
                }
            }
        }
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = (ConfigurableApplicationContext) applicationContext;
    }
}
